package com.edu.app.controller.app.teacher;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.app.bean.app.teacher.SysCustomerActFeedback;
import com.edu.app.bean.core.*;
import com.edu.app.bean.linkbeans.SysCustomerActivity;
import com.edu.app.constant.ErrorConstant;
import com.edu.app.constant.StaticConstant;
import com.edu.app.constant.SysMessage;
import com.edu.app.service.sys.app.teacher.SysCutomerActFeedbackService;
import com.edu.app.service.sys.core.SysActivityService;
import com.edu.app.service.sys.core.SysListOfValueService;
import com.edu.app.service.sys.core.SysUserService;
import com.edu.app.service.sys.linkservices.SysCustomerActivityService;
import com.edu.app.service.sys.linkservices.SysCustomerTraceService;
import com.edu.app.threadlocal.TenantContext;
import com.edu.app.util.CommonUtils;
import com.edu.app.util.ErrorUtil;
import com.edu.app.util.JWTUtil;
import com.edu.app.util.MsgUtil;

import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping(value = "/api/teachers/customer_act_feedback")
@RestController
public class SysCustomerActFeedbackController {

    @Autowired
    private SysCutomerActFeedbackService sysCutomerActFeedbackService;

    @Autowired
    private SysCustomerActivityService sysCustomerActivityService;

    @Autowired
    private SysActivityService sysActivityService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysListOfValueService sysListOfValueService;

    @Autowired
    private SysCustomerTraceService sysCustomerTraceService;

    @GetMapping(value = "")
    @RequiresAuthentication
    public ModelMap getObjectList(){
        try{
            List<SysCustomerActFeedback> sysCustomerActFeedbackList = sysCutomerActFeedbackService.getObjectList();
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_ACT_FEEDBACK_SUCCEED, StaticConstant.CUSTOMER_ACT_FEEDBACK_LIST, sysCustomerActFeedbackList);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping(value = "/{id}")
    public ModelMap getObjectById(@PathVariable Integer id){
        try{
            TenantContext.setNeedTenantId(Boolean.FALSE);
            SysCustomerActFeedback sysCustomerActFeedback = sysCutomerActFeedbackService.getObjectById(id);
            TenantContext.setNeedTenantId(Boolean.TRUE);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_ACT_FEEDBACK_SUCCEED, StaticConstant.CUSTOMER_ACT_FEEDBACK, sysCustomerActFeedback);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

    @GetMapping("/pages")
    @RequiresAuthentication
    public ModelMap getObjectByPage(@RequestParam Integer offset, @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCutomerActFeedbackService.findItemByPage(offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_ACT_FEEDBACK_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/pages/getObjectListOrderByTime/{id}")
    @RequiresAuthentication
    public ModelMap getObjectListOrderByTime(@PathVariable Integer id, @RequestParam Integer offset, @RequestParam Integer limit) {

        try {
            PageInfo pageInfo = sysCutomerActFeedbackService.getObjectListOrderByTime(id, offset, limit);
            return MsgUtil.retMsg(SysMessage.GET_CUSTOMER_ACT_FEEDBACK_BY_PAGE_SUCCEED, "page_info", pageInfo);
        } catch (Exception e) {
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }
    }

    @GetMapping("/getFeedbackIdWithCustomerAndActId")
    @RequiresAuthentication
    public ModelMap getFeedbackIdWithCustomerAndActId(@RequestParam Integer customer_id, @RequestParam Integer activity_id){
        try{
            Integer id = sysCutomerActFeedbackService.getFeedbackIdWithCustomerAndActId(customer_id, activity_id);
            return MsgUtil.retMsg(SysMessage.GET_FEEDBACK_ID_SUCCEED, "id", id);
        }catch (Exception e){
            return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
        }

    }

    @PostMapping(value = "")
    @RequiresAuthentication
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public ModelMap addObject(@RequestHeader("Authorization") String token,
                              @RequestBody String sysCustomerActFeedbackStrList,
                              @RequestParam String sysCustomerListStr,
                              @RequestParam Integer activity_id){
        ModelMap map = new ModelMap();
        try{
            String username = JWTUtil.getUsername(token);
            JSONObject obj = (JSONObject) JSON.parse(sysCustomerActFeedbackStrList);
            List<SysCustomerActFeedback> sysCustomerActFeedbackList = JSON.parseArray(obj.get("sysCustomerActFeedbackStrList").toString(), SysCustomerActFeedback.class);
            //SysCustomerActFeedback[] sysCustomerActFeedbackList = (SysCustomerActFeedback[])JSON.parse(sysCustomerActFeedbackListStr);
            List<SysCustomer> sysCustomerList = JSON.parseArray(sysCustomerListStr, SysCustomer.class);

            for(SysCustomerActFeedback sysCustomerActFeedback: sysCustomerActFeedbackList){
                for(SysCustomer sysCustomer: sysCustomerList ){
                    if(sysCustomerActFeedback.getName().equalsIgnoreCase(sysCustomer.getName())){
                        SysCustomerActivity sysCustomerActivity = sysCustomerActivityService.getCustomerActivity(sysCustomer.getId(), activity_id);
                        sysCustomerActFeedback.setCustomer_activity_id(sysCustomerActivity.getId());
                        sysCustomerActFeedback.initializeSystemColumns(username);
                        sysCutomerActFeedbackService.add(sysCustomerActFeedback);

                        //Adding corresponding trace details
                        SysActivity sysActivityTmp = sysActivityService.getObjectById(activity_id);
                        SysUser sysUserTmp = sysUserService.getUserByName(username);
                        SysListOfValue sysListOfValueTmp = sysListOfValueService.getObjectById(sysActivityTmp.getType_id());
                        String content = "完成反馈" + sysListOfValueTmp.getValue() + "课。" + "老师：" + sysUserTmp.getNickname() + "，时间：" + CommonUtils.dateToString(sysActivityTmp.getTime());
                        SysCustomerTrace sysCustomerTrace = new SysCustomerTrace();
                        sysCustomerTrace.initializeSystemColumns(username);
                        sysCustomerTrace.setContent(content);
                        sysCustomerTrace.setCustomer_id(sysCustomer.getId());
                        sysCustomerTraceService.add(sysCustomerTrace);
                    }
                }
            }

            //update the activity status to 2, means the feedback of this activity has been completed.
            SysActivity sysActivity = sysActivityService.getObjectById(activity_id);
            sysActivity.setStatus(2);
            sysActivityService.update(sysActivity);

            map = MsgUtil.retMsg(SysMessage.ADD_CUSTOMER_ACT_FEEDBACK_SUCCEED, null, null);

        }catch (org.springframework.dao.DuplicateKeyException e){
            map = ErrorUtil.retErrMsg(ErrorConstant.CUSTOMER_FEEDBACK_ALREADY_EXISTS);
            //update the activity status to 2, means the feedback of this activity should be completed.
            SysActivity sysActivity = sysActivityService.getObjectById(activity_id);
            sysActivity.setStatus(2);
            sysActivityService.update(sysActivity);
        }catch(Exception e){
            map = ErrorUtil.retErrMsg(e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return map;
    }

    @DeleteMapping(value = "")
    @RequiresAuthentication
    public ModelMap deleteObject(@RequestParam Integer id){
        try{
            sysCutomerActFeedbackService.delete(id);
            return MsgUtil.retMsg(SysMessage.DELETE_CUSTOMER_ACT_FEEDBACK_SUCCEED, null, null);
        }catch(Exception e){
            return ErrorUtil.retErrMsg(e);
        }
    }

}
